package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"shop_srv/cache"
	"shop_srv/models"
	"time"

	"shop_srv/internal/svc"
	"shop_srv/shop"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShowGoodsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShowGoodsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShowGoodsLogic {
	return &ShowGoodsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ShowGoodsLogic) ShowGoods(in *shop.ShowGoodsRequest) (*shop.ShowGoodsResponse, error) {
	// todo: add your logic here and delete this line

	var goods models.Goods

	key := fmt.Sprintf("goodsId_%d", in.GoodsId)
	codeData, _ := cache.Rdb.Get(l.ctx, key).Result()

	if codeData == "" {
		models.DB.Where("id=?", in.GoodsId).Find(&goods)
		jsonData, _ := json.Marshal(goods)
		cache.Rdb.Set(l.ctx, key, jsonData, time.Minute*5)
	} else {
		err := json.Unmarshal([]byte(codeData), &goods)
		if err != nil {
			return nil, err
		}
	}
	return &shop.ShowGoodsResponse{
		GoodsId: in.GoodsId,
		Title:   goods.Title,
		Price:   float32(goods.Price),
		Stock:   goods.Stock,
		Status:  goods.GoodsStatus,
	}, nil
}
